﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Timers;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;


namespace server
{
    public partial class Server : Form
    {
        private bool flag = false,flag_tx = false;
        private bool flag_video = false;
        private bool flag_window = false;
        private bool flag_conn = false;
        private UInt16 port = 1988, video_port, portaClip;
        private int top = 0, left = 0, height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
        private int width = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
        private Img form1;
        private chat my_chat;
        private string password;
        private IntPtr hwnd;
        private TcpListener l, listClip;
        private String path = Path.Combine(Environment.CurrentDirectory, @".\img_config.conf");
        private String path2 = Path.Combine(Environment.CurrentDirectory, @".\km_server.conf");
        private Img_settings form2 ;
        private const int CP_NOCLOSE_BUTTON = 0x200;
        private char pause_key = 'p';

        public delegate void newMessageCallback(string message);

        public Server()
        {
            InitializeComponent();
            if (File.Exists(path2))
            {
                using (StreamReader LeggiConf = File.OpenText(path2))
                {
                    UtenteConnesso.Text = LeggiConf.ReadLine();
                    my_port.Text = LeggiConf.ReadLine();
                    port = UInt16.Parse(my_port.Text);
                }
                flag = true;
            }
        }

        private void impostazioniToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (flag_video)
            {
                if (form1.v_flag)
                {
                    VideoButton.Image = ((System.Drawing.Image)(Properties.Resources.play_1));
                    form1.v_flag = false;
                }
                else
                {
                    VideoButton.Image = ((System.Drawing.Image)(Properties.Resources.pause));
                    form1.v_flag = true;
                }
            }
            else
            {
                if (!flag || !flag_tx)
                {
                    MessageBox.Show("Cannot start connection!\nYou have to set password, port and trasmission parameters before starting!");
                }
                else
                {
                    l = new TcpListener(IPAddress.Parse("0.0.0.0"), port);
                    l.Start();
                    TcpListener lst = new TcpListener(IPAddress.Parse("0.0.0.0"), 0);
                    lst.Start();
                    string temp = lst.LocalEndpoint.ToString();
                    string[] str = temp.Split(':');
                    video_port = UInt16.Parse(str[1]);
                    listClip = new TcpListener(IPAddress.Parse("0.0.0.0"), 0);
                    listClip.Start();
                    String strTmp = listClip.LocalEndpoint.ToString();
                    String[] portaClipboard = strTmp.Split(':');
                    portaClip = UInt16.Parse(portaClipboard[1]);

                    ChatHandler();
                    if (File.Exists(path))
                    {
                        using (StreamReader LeggiConf = File.OpenText(path))
                        {
                            String settaggio = LeggiConf.ReadLine();
                            if (settaggio.Equals("desktop"))
                            {
                                int scroll_left = int.Parse(LeggiConf.ReadLine());
                                int scroll_right = int.Parse(LeggiConf.ReadLine()) - 9;
                                int scroll_top = int.Parse(LeggiConf.ReadLine());
                                int scroll_bottom = int.Parse(LeggiConf.ReadLine()) - 9;
                                left = scroll_left * System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width / 100;
                                width = (scroll_right - scroll_left) * System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width / 100;
                                top = scroll_top * System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height / 100;
                                height = (scroll_bottom - scroll_top) * System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height / 100;
                                flag_window = false;
                            }
                        }
                    }

                    if (flag_window)
                    {
                        form1 = new Img(top, left, width, height, hwnd, lst);
                    }
                    else
                    {
                        form1 = new Img(top, left, width, height, lst);
                    }
                    form1.Show();
                    flag_video = true;
                    VideoButton.Image = ((System.Drawing.Image)(Properties.Resources.pause));
                    flag_conn = true;
                }
            }
        }

        private void impostazioniToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (flag_video)
            {
                form1.set_exit = true;
                form1.Close();
                my_chat.Close();
                l.Stop();
                flag_video = false;
                VideoButton.Image = ((System.Drawing.Image)(Properties.Resources.play_1));
                flag_conn = false;
            }
        }

        private void impostazioniToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            Impostazioni form;
            if (!flag)
            {
                form = new Impostazioni();
            }
            else
            {
                form = new Impostazioni(port, UtenteConnesso.Text);
            }
            DialogResult result = form.ShowDialog();
            if (result == DialogResult.OK)
            {
                flag = true;
                port = UInt16.Parse(form.port);
                my_port.Text = form.port;
                UtenteConnesso.Text = form.user;
                password = form.pass;
            }
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            form2 = new Img_settings();
            if (!flag_conn)
            {
                DialogResult res = form2.ShowDialog();
                if (res == DialogResult.OK)
                {
                    flag_tx = true;
                    top = form2.gettop;
                    left = form2.getleft;
                    height = form2.getheight;
                    width = form2.getwidth;
                    flag_window = form2.window;
                    hwnd = form2.cur_hwnd;
                }
            }
            else
            {
                
                bool tmp = form1.v_flag;
                form1.v_flag = false;
                DialogResult res = form2.ShowDialog();
                if (res == DialogResult.OK)
                {
                    top = form2.gettop;
                    form1.i_top = form2.gettop;
                    left = form2.getleft;
                    form1.i_left = form2.getleft;
                    height = form2.getheight;
                    form1.i_height = form2.getheight;
                    width = form2.getwidth;
                    form1.i_width = form2.getwidth;
                    flag_window = form2.window;
                    form1.i_window = form2.window;
                    hwnd = form2.cur_hwnd;
                    form1.i_hwnd = form2.cur_hwnd;
                    form1.valid_window = true;
                }
                form1.v_flag = tmp;
            }
        }

        private void ChatHandler()
        {
            try
            {
                my_chat = new chat(UtenteConnesso.Text, video_port, portaClip, password, l, listClip);
                my_chat.txtbox = "Waiting for connections... ";
                my_chat.Show();
            }
            catch
            {
                my_chat.Close();
                Thread.Sleep(100);
                MessageBox.Show("Interrup chatting...");
            }
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams myCp = base.CreateParams;
                myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON;
                return myCp;
            }
        }

        private void CloseButton_Click(object sender, EventArgs e)
        {
            int nClienti = my_chat.getNClient;
            for (int j = 0; j < nClienti; j++)
            {
                try
                {
                    my_chat.getChatThread[j].Abort();
                    my_chat.getChatCon[j].Close();
                }
                catch { ; }
                try
                {
                    my_chat.getClipThread[j].Abort();
                    my_chat.getClipCon[j].Close();   
                }
                catch { ; }
                try
                {
                    form1.getThreadReceiver[j].Abort();
                    form1.getImgTcpReceiver[j].Close();
                }
                catch { ; }
            }
            try
            {
                my_chat.getAccChatThread.Abort();
            }
            catch{ ; }
            try
            {
                form1.accClient.Abort();
            }
            catch { ;}
            try
            {
                my_chat.getAccClipThread.Abort();
            }
            catch { ; }
            try
            {
                l.Stop();
            }
            catch{ ; }
            try
            {
                listClip.Stop();
            }
            catch { ; }
            try
            {
                form1.getTcpListImg.Stop();
            }
            catch { ;}
            
            form1.set_exit = true;
            form1.Close();
            this.Close();
        }
        
        private void Server_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == pause_key)
            {
                if (flag_video)
                {
                    if (form1.v_flag)
                    {
                        VideoButton.Image = ((System.Drawing.Image)(Properties.Resources.play_1));
                        form1.v_flag = false;
                    }
                    else
                    {
                        VideoButton.Image = ((System.Drawing.Image)(Properties.Resources.pause));
                        form1.v_flag = true;
                    }
                }
            }
        }

        private void configurePauseButtonToolStripMenuItem_Click(object sender, EventArgs e)
        {
            pause_set form_pause = new pause_set();
            form_pause.ShowDialog();
            pause_key = form_pause.getKey;
        }
    }
}
